<template>
	<ln-modal
		width="680px"
		max-height="650"
		:title="title"
		:mask-closable="false"
		:on-after-enter="onModalShow"
	>
		<n-form
			ref="formRef"
			:model="form"
			:rules="rules"
			:disabled="props.modalType === ModalTypeEnum.detail"
			label-placement="left"
			require-mark-placement="right-hanging"
			label-width="120px"
		>
			<n-grid :cols="24" :x-gap="24">
				<n-form-item-gi :span="11" :label="$t('common.userName')" path="userName">
					<ln-input v-model:value="form.userName" :placeholder="$t('msg.input')" />
				</n-form-item-gi>
				<n-form-item-gi :span="11" :label="$t('common.phone')" path="phone">
					<ln-input v-model:value="form.phone" :placeholder="$t('msg.input')" />
				</n-form-item-gi>
				<n-form-item-gi :span="11" :label="$t('common.email')" path="email">
					<n-auto-complete
						v-model:value="form.email"
						:options="emailOptions"
						:placeholder="$t('msg.input')"
						:input-props="{ autocomplete: 'disabled' }"
					/>
				</n-form-item-gi>
				<n-form-item-gi :span="11" :label="$t('common.loginName')" path="loginName">
					<ln-input v-model:value="form.loginName" :placeholder="$t('msg.input')" />
				</n-form-item-gi>
				<n-form-item-gi :span="11" :label="$t('common.password')" path="formPassword">
					<ln-input
						v-model:value="form.formPassword"
						type="password"
						:placeholder="$t('msg.input')"
					/>
				</n-form-item-gi>
				<n-form-item-gi :span="11" :label="$t('common.reconfirm')" path="repassword">
					<ln-input
						v-model:value="form.repassword"
						type="password"
						:placeholder="$t('msg.input')"
					/>
				</n-form-item-gi>
				<n-form-item-gi :span="22" :label="$t('common.description')" path="description">
					<ln-input
						v-model:value="form.description"
						type="textarea"
						:placeholder="$t('msg.select')"
					/>
				</n-form-item-gi>
				<n-form-item-gi :span="22" :label="$t('common.accountState')" path="status">
					<n-switch v-model:value="form.status" :checked-value="0" :unchecked-value="1" />
				</n-form-item-gi>
				<n-form-item-gi :span="24" :label="$t('common.role')" path="roleIds">
					<n-checkbox-group v-model:value="form.roleIds">
						<n-space item-style="display: flex;">
							<n-checkbox
								v-for="item in roleStroe.roleList"
								:key="item.id"
								class="check-item"
								:value="item.id"
								:label="item.name"
							/>
						</n-space>
					</n-checkbox-group>
				</n-form-item-gi>
			</n-grid>
		</n-form>
		<template #footer>
			<div style="margin-top: 20px">
				<n-button
					v-if="props.modalType === ModalTypeEnum.detail"
					type="primary"
					@click="handleUpdateClick"
					>{{ $t('btn.update') }}</n-button
				>
				<n-button v-else type="primary" @click="handleSaveClick">{{ $t('btn.save') }}</n-button>
				<n-button @click="handleCloseClick(false)">{{ $t('btn.cancel') }}</n-button>
			</div>
		</template>
	</ln-modal>
</template>

<script lang="ts" setup>
import { useI18n } from 'vue-i18n';
import { Md5 } from 'ts-md5';
import type { PropType } from 'vue';
import type { UserListRow } from '@/api/system/account';
import { addUser, updateUser } from '@/api/system/account';
import { useRoleStore } from '@/store/modules/role';
import { useMessage } from 'naive-ui';
import type { FormInst, FormRules, FormItemRule } from 'naive-ui';
import { ModalTypeEnum } from '@/utils/enum';
import type { ModalTypeParam } from '@/utils/enum';
import { titleFormatter } from '@/utils/formatter';
import { validateEmail, validateArrRequired, validateRepeat } from '@/utils/validate';

const { t } = useI18n();
const props = defineProps({
	modalData: {
		type: Object as PropType<UserListRow | {}>,
		default: () => {},
	},
	modalType: {
		type: [String, Number] as PropType<ModalTypeParam>,
		default: ModalTypeEnum.add,
	},
});
const message = useMessage();
const emit = defineEmits(['close', 'update']);
const title = computed(() => titleFormatter(props.modalType));
// form
const formRef = ref<FormInst | null>();
const baseForm: UserListRow = {
	userName: '',
	phone: '',
	roleIds: [],
	email: '',
	loginName: '',
	status: 0,
	password: '',
	formPassword: '',
	repassword: '',
	description: '',
};
const form = ref<UserListRow>({ ...baseForm });
const emailOptions = computed(() => {
	return ['@gmail.com', '@163.com', '@qq.com'].map(suffix => {
		const prefix = form.value.email.split('@')[0];
		return {
			label: prefix + suffix,
			value: prefix + suffix,
		};
	});
});
// rule
const rules: FormRules = {
	userName: { required: true, trigger: ['blur'], message: t('msg.input') },
	phone: { required: true, trigger: ['blur'], message: t('msg.input') },
	email: {
		required: true,
		trigger: ['blur'],
		validator: (rule, value) => validateEmail(rule, value),
	},
	loginName: { required: true, trigger: ['blur'], message: t('msg.input') },
	formPassword: [
		{ required: true, trigger: ['blur'], message: t('msg.input') },
		{ min: 6, trigger: ['blur'], message: t('msg.passwordLength') },
	],
	repassword: [
		{ required: true, trigger: ['blur'], message: t('msg.input') },
		{
			validator: (rule, value) => validateRepeat(rule, value, form.value.formPassword),
			message: t('msg.password'),
			trigger: 'blur',
		},
	],
	roleIds: {
		required: true,
		trigger: ['blur'],
		message: t('msg.userPower'),
		validator: (rule, value) => validateArrRequired(rule, value),
	},
};
const roleStroe = useRoleStore();

// 初始化
function onModalShow() {
	if (props.modalType === ModalTypeEnum.add) {
		form.value = { ...baseForm };
	} else {
		const params = JSON.parse(JSON.stringify(props.modalData)) as UserListRow;
		params.formPassword = params.repassword = params.password;
		form.value = params;
	}
}

// 保存
function handleSaveClick() {
	formRef.value?.validate(async errors => {
		if (!errors) {
			const params = { ...unref(form) };
			if (props.modalType === ModalTypeEnum.add) {
				params.password = Md5.hashStr(params.formPassword!);
				await addUser(params);
			} else {
				console.log(params);
				if (params.password !== params.formPassword) {
					params.password = Md5.hashStr(params.formPassword!);
				}
				await updateUser(params);
			}
			message.success(t('msg.operationCompleted'));
			handleCloseClick(true);
		}
	});
}
// 关闭
function handleCloseClick(data?: boolean) {
	emit('close', data);
}
// 编辑
function handleUpdateClick() {
	emit('update');
}
</script>

<style lang="scss" scoped>
.check-item {
	min-width: 120px;
}
</style>
